/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sputty.classes;

import java.io.IOException;
import java.io.InputStream;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import sputty.terminal.SwingTerminal;

/**
 *
 * @author mauro
 */
public class RemoteConsumer extends Thread {
    
    char[][] lines;
    int posy;
    int posx;
    int y;
    int x;
    InputStream in;
    MyTerminalArea TerminalArea;
    TerminalAreaExtended TerminalEx;
    SwingTerminal term;
    
    public RemoteConsumer(int y, int x, InputStream in, MyTerminalArea TerminalArea){
        lines = new char[y][];
        posy = 0;
        posx = 0;        
        this.y = y;
        this.x = x;
        this.in = in;
        this.TerminalArea = TerminalArea;
    }
    
    public RemoteConsumer(int y, int x, InputStream in, TerminalAreaExtended TerminalEx){
        lines = new char[y][];
        posy = 0;
        posx = 0;        
        this.y = y;
        this.x = x;
        this.in = in;
        this.TerminalEx = TerminalEx;
    }
    
    public RemoteConsumer(int y, int x, InputStream in, SwingTerminal term){
        lines = new char[y][];
        posy = 0;
        posx = 0;        
        this.y = y;
        this.x = x;
        this.in = in;
        this.term = term;
    }
    
    public void run(){

        //final byte[] buf = new byte[8192];
        final byte[] buf = new byte[1024];
        try {
            while (true) {
                final int len = in.read(buf);
                if (len == -1) {
                    break;
                }
                if(TerminalArea != null){
                    String readed = new String(buf,0,len);
                    TerminalArea.append(readed);
                    // Make sure the last line is always visible
                    TerminalArea.setCaretPosition(TerminalArea.getDocument().getLength());

                    // Keep the text area down to a certain character size
                    int idealSize = 8000;
                    int maxExcess = 4000;
                    int excess = TerminalArea.getDocument().getLength() - idealSize;
                    if (excess >= maxExcess) {
                        TerminalArea.replaceRange("", 0, excess);
                    }
                }else{
                    if(term == null){
                        TerminalEx.run();
                    }else{
                        term.run();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
    
}
